package com.lagou.server;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread{

    private Socket socket;

    private Map<String,Map<String,HttpServlet>> appServletMap;

    public RequestProcessor(Socket socket,Map<String,Map<String,HttpServlet>> appServletMap){
        this.socket = socket;
        this.appServletMap = appServletMap;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            //从输入流中获取请求信息

            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            int i = request.getUrl().indexOf("/", 1);
            //指向项目的路径
            String appUrl = request.getUrl().substring(1,i);
            //指向 servlet的路径
            String pathUrl = request.getUrl().substring(i);

            HttpServlet httpServlet = appServletMap.get(appUrl) == null ? null : appServletMap.get(appUrl).get(pathUrl);
            if(httpServlet == null){
                response.outputHtml(request.getUrl());
            }else {
                httpServlet.service(request,response);
            }
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
